use serde::{Deserialize, Serialize};
use thiserror::Error;

/// 应用程序错误类型
#[derive(Error, Debug, Clone, Serialize, Deserialize)]
pub enum AppError {
    #[error("数据库错误: {message}")]
    Database { message: String },

    #[error("配置错误: {message}")]
    Config { message: String, key: Option<String> },

    #[error("文件系统错误: {message}")]
    FileSystem { message: String, path: Option<String> },

    #[error("网络错误: {message}")]
    Network { message: String, url: Option<String> },

    #[error("验证错误: {message}")]
    Validation { message: String, field: Option<String> },

    #[error("序列化错误: {message}")]
    Serialization { message: String, data_type: Option<String> },

    #[error("系统错误: {message}")]
    System { message: String, code: Option<i32> },

    #[error("未知错误: {message}")]
    Unknown { message: String },
}

/// 错误严重程度
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ErrorSeverity {
    /// 信息性错误，不影响功能
    Info,
    /// 警告，可能影响部分功能
    Warning,
    /// 错误，影响功能但不会崩溃
    Error,
    /// 严重错误，可能导致崩溃
    Critical,
}

impl AppError {
    /// 创建数据库错误
    pub fn database<S: Into<String>>(message: S) -> Self {
        Self::Database {
            message: message.into(),
        }
    }

    /// 创建配置错误
    pub fn config<S: Into<String>>(message: S) -> Self {
        Self::Config {
            message: message.into(),
            key: None,
        }
    }

    /// 创建文件系统错误
    pub fn filesystem<S: Into<String>>(message: S) -> Self {
        Self::FileSystem {
            message: message.into(),
            path: None,
        }
    }

    /// 创建验证错误
    pub fn validation<S: Into<String>>(message: S) -> Self {
        Self::Validation {
            message: message.into(),
            field: None,
        }
    }

    /// 获取错误的默认严重程度
    pub fn default_severity(&self) -> ErrorSeverity {
        match self {
            AppError::Database { .. } => ErrorSeverity::Critical,
            AppError::Config { .. } => ErrorSeverity::Error,
            AppError::FileSystem { .. } => ErrorSeverity::Error,
            AppError::Network { .. } => ErrorSeverity::Warning,
            AppError::Validation { .. } => ErrorSeverity::Warning,
            AppError::Serialization { .. } => ErrorSeverity::Error,
            AppError::System { .. } => ErrorSeverity::Critical,
            AppError::Unknown { .. } => ErrorSeverity::Error,
        }
    }

    /// 获取错误类型字符串
    pub fn error_type(&self) -> &'static str {
        match self {
            AppError::Database { .. } => "Database",
            AppError::Config { .. } => "Config",
            AppError::FileSystem { .. } => "FileSystem",
            AppError::Network { .. } => "Network",
            AppError::Validation { .. } => "Validation",
            AppError::Serialization { .. } => "Serialization",
            AppError::System { .. } => "System",
            AppError::Unknown { .. } => "Unknown",
        }
    }
}
